import React, {Component} from 'react';
import {Image, ScrollView, FlatList, Text, TouchableOpacity, View, AsyncStorage, Modal, WebView} from 'react-native';
import {BasicStyle} from "../../../style/BasicStyle";
import {ShopListStyle} from "../../../style/ShopStyle/ShopListStyle";
import CountEmitter from './../../utils/event/CountEmitter';
import {ShopStyle} from "../../../style/ShopStyle/ShopStyle";
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import Swiper from 'react-native-swiper';
import {RadioButtons} from 'react-native-radio-buttons';
import FetchUtils from './../../utils/FetchUtils'
import {ShopDetailStyle} from "../../../style/ShopStyle/ShopDetailStyle";
import utils from './../../utils/utils';

export default class ShopDetail extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: navigation.state.params ? navigation.state.params.name : null,
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerRight: <TouchableOpacity style={ShopDetailStyle.rightTopBut}
                                       onPress={() => navigation.state.params ? navigation.state.params.productDetailBut() : null}><Text
            style={ShopDetailStyle.rightTopButText}>产品说明</Text></TouchableOpacity>,
    });

    constructor() {
        super();
        this.state = ({
            loadingStatus: false,
            product: null,
            productColor: null,
            productSize: null,
            productImgs: [],
            shopCarNum: 0,
            shopCarColorMsg: '请选择颜色',
            shopCarColorOption: null,
            shopCarSizeMsg: '请选择尺寸',
            shopCarSizeOption: null,
            isShowSwiper: false,
            modalStatus: false,
            modalShopCarStatus: false,
        })
    }

    componentDidMount() {

        if (this.props.navigation.state.params) {
            /*重新请求数据*/
            AsyncStorage.getItem("XToken").then((xToken) => {
                if (!this.state.lastStatus) {
                    this.setState({loadingStatus: true});
                    let params = {
                        productId: this.props.navigation.state.params.productId,
                    };
                    FetchUtils.getWithHeader(utils.apiUrl + '/shop/proDatail', xToken, params, (res) => {
                        console.log(res);
                        if (res.code === 200) {
                            let allImgs = [];
                            let mainImg = res.apiData.product.mainImg;
                            let imgs = '';
                            if(res.apiData.product.imgs.includes(",")){
                                imgs = res.apiData.product.imgs.split(", ");
                            }else {
                               imgs = res.apiData.product.imgs;
                            }
                            allImgs.push(mainImg);

                            let swiperView = [];
                            allImgs.concat(imgs).map((item, index) => {
                                swiperView.push(
                                    <Image key={index} source={{uri: utils.qiniuUrl + item + utils.qiniu500Url}}
                                           style={ShopDetailStyle.swiperImg}/>)

                            });

                            this.setState({
                                loadingStatus: false,
                                product: res.apiData.product,
                                productColor: res.apiData.productColor,
                                productSize: res.apiData.productSize,
                                productImgs: swiperView,
                            });

                            /*动态改变title*/
                            this.props.navigation.setParams({
                                name: res.apiData.product.name,
                                productDetailBut: this._productDetailBut,
                            });

                            setTimeout(() => {
                                this.setState({
                                    isShowSwiper: true,
                                })
                            }, 0);

                        } else {
                            this.setState({
                                loadingStatus: false,
                            });
                            Toast.showShortTop(res.apiData);
                        }
                    })
                }
            });
        }
    }

    render() {
        /*轮播图*/
        let myswiper = !this.state.isShowSwiper ? null :
            <Swiper
                horizontal={true}
                showsButtons={false}
                autoplay={false}
                showsPagination={!this.state.modalShopCarStatus}
            >
                {this.state.productImgs}
            </Swiper>;
        /*购物车单选*/
        let priceView = this.state.listPrice ?
            <RadioButtons
                options={priceMark}
                onSelection={this.setRadioButtonsSelectedOption.bind(this)}
                renderOption={this.renderRadioButtonsOption}
                renderContainer={this.renderRadioButtonsContainer}
            />
            :
            <Text>无数据</Text>;
        return (
            <View style={BasicStyle.containerView}>
                <Modal
                    animationType={"slide"}
                    transparent={true}
                    visible={this.state.modalStatus}
                    onRequestClose={() => {
                        this.setState({
                            modalStatus: false,
                        })
                    }}
                >
                    <View style={ShopDetailStyle.modalView}>
                        <View style={ShopDetailStyle.modalViewView}>
                            <View style={ShopDetailStyle.modalViewViewButView}>
                                <TouchableOpacity onPress={() => {
                                    this.setState({
                                        modalStatus: false,
                                    })
                                }}>
                                    <Image
                                        source={require('./../../../img/close_but.png')}
                                        style={ShopDetailStyle.modalViewViewButImg}/>
                                </TouchableOpacity>
                            </View>

                            <WebView
                                automaticallyAdjustContentInsets={true}
                                bounces={false}
                                injectedJavaScript=
                                    "
     var imgs = document.getElementsByTagName('img');
     for (var i = 0; i < imgs.length; ++i) {
        var img = imgs[i];
        img.style.width = '100%';
        img.style.height = 'auto';
     }
     "
                                javaScriptEnabled={true}
                                scalesPageToFit={true}
                                source={{html: this.state.product ? this.state.product.content : null}}
                                style={ShopDetailStyle.modalWebView}/>
                            <View style={ShopDetailStyle.modalFooterView}>
                            </View>
                        </View>
                    </View>
                </Modal>

                <View style={ShopDetailStyle.swiperView}>
                    {myswiper}
                </View>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>

                <Modal
                    animationType={"slide"}
                    transparent={true}
                    visible={this.state.modalShopCarStatus}
                    onRequestClose={() => {
                        this.setState({
                            modalShopCarStatus: false,
                        })
                    }}
                >

                    <View style={[BasicStyle.containerView, ShopDetailStyle.shopCarModalView]}>
                        <TouchableOpacity style={ShopDetailStyle.shopCarModalViewBut} onPress={() =>
                            this.setState({
                                modalShopCarStatus: false,
                            })}/>
                        <ScrollView
                            style={ShopDetailStyle.shopCarModalScrollView}>
                            <View>
                                <View>
                                    <Text style={ShopDetailStyle.shopCarRadioTitleText}>颜色</Text>
                                    {
                                        this.state.productColor ?
                                            this._radioColorButtons(this.state.productColor)
                                            :
                                            null
                                    }
                                </View>

                                <View>
                                    <Text style={ShopDetailStyle.shopCarRadioTitleText}>尺寸</Text>
                                    {
                                        this.state.productSize ?
                                            this._radioSizeButtons(this.state.productSize)
                                            :
                                            null
                                    }
                                </View>

                                <View style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                    borderBottomWidth: utils.autoheight(0.5),
                                    borderColor: '#979797',
                                }}>
                                    <Text style={ShopDetailStyle.shopCarRadioTitleText}>数量</Text>
                                    <View style={ShopDetailStyle.shopCarModalNumView}>
                                        <TouchableOpacity style={ShopDetailStyle.shopCarModalNumViewButRight}
                                                          onPress={() => {
                                                              if (this.state.shopCarNum > 0) {
                                                                  this.setState({
                                                                      shopCarNum: this.state.shopCarNum - 1,
                                                                  })
                                                              }
                                                          }}>
                                            <Image style={ShopDetailStyle.shopCarModalNumViewButImg}
                                                   source={require('./../../../img/remove.png')}
                                            />
                                        </TouchableOpacity>
                                        <Text style={{
                                            fontSize: utils.setSpText(21),
                                            color: '#000'
                                        }}>{this.state.shopCarNum}</Text>
                                        <TouchableOpacity style={ShopDetailStyle.shopCarModalNumViewButLeft}
                                                          onPress={() => {
                                                              this.setState({
                                                                  shopCarNum: this.state.shopCarNum + 1,
                                                              })
                                                          }}>
                                            <Image style={ShopDetailStyle.shopCarModalNumViewButImg}
                                                   source={require('./../../../img/add.png')}/>
                                        </TouchableOpacity>
                                    </View>
                                </View>

                                <View style={ShopDetailStyle.shopCarModalSelectedView}>
                                    <Text style={ShopDetailStyle.shopCarRadioTitleText}>已选：</Text>
                                    <Text
                                        style={ShopDetailStyle.shopCarRadioTitleText}>“{this.state.shopCarColorMsg}”，“{this.state.shopCarSizeMsg}”</Text>

                                </View>

                                <View style={ShopDetailStyle.shopCarModalSubmitView}>
                                    <TouchableOpacity style={ShopDetailStyle.shopCarModalSubmitBut}
                                                      onPress={this._addShopCar.bind(this)}>
                                        <Text style={ShopDetailStyle.shopCarText}>加入购物车</Text>
                                    </TouchableOpacity>

                                </View>


                            </View>


                        </ScrollView>
                    </View>

                </Modal>

                {!this.state.modalShopCarStatus ?
                    <View style={ShopDetailStyle.bottomView}>
                        <TouchableOpacity onPress={this._clickShopCar.bind(this)} style={ShopDetailStyle.shopCarBut}>
                            <Text style={ShopDetailStyle.shopCarText}>加入购物车</Text>
                        </TouchableOpacity>

                        <View style={ShopDetailStyle.priceView}>
                            <Text
                                style={[ShopStyle.listTitleMarkViewText, ShopDetailStyle.oldPriceText]}>{this.state.product ? "¥ " + utils.toDecimal2(this.state.product.oldPrice) : ""}</Text>
                            <Text
                                style={ShopDetailStyle.nowPriceText}>{this.state.product ? "¥ " + utils.toDecimal2(this.state.product.nowPrice) : ""}</Text>
                        </View>
                    </View>
                    :
                    null
                }
            </View>
        )
    }

    /*产品详情*/
    _productDetailBut = () => {
        this.setState({
            modalStatus: true,
        })
    };

    /*点击“加入购入车”这个按钮*/
    _clickShopCar = () => {
        this.setState({
            modalShopCarStatus: true,
        })
    };

    /*确认“加入购物车”*/
    _addShopCar = () => {
        if (this.state.shopCarColorMsg === '请选择颜色') {
            Toast.showShortBottom("亲~还没选择颜色喔~")
        } else if (this.state.shopCarSizeMsg === '请选择尺寸') {
            Toast.showShortBottom("亲~还没选择尺寸喔~")
        } else if (this.state.shopCarNum === 0) {
            Toast.showShortBottom("亲~还没选择数量喔~")
        } else {
            this.setState({
                loadingStatus: true,
            });
            AsyncStorage.getItem("userId").then((userId) => {
                // AsyncStorage.removeItem("shopCar_" + userId);
                AsyncStorage.getItem("shopCar_" + userId).then((shopCar) => {
                    /*如果购物车为空*/
                    console.log(JSON.parse(shopCar));
                    if (JSON.parse(shopCar) === null) {
                        let shopCarParam = [{
                            proId: this.state.product.id,
                            proMainImg: this.state.product.mainImg,
                            proName: this.state.product.name,
                            proColor: this.state.shopCarColorMsg,
                            proSize: this.state.shopCarSizeMsg,
                            proNum: this.state.shopCarNum,
                            proNowPrice: this.state.product.nowPrice,
                            proOldPrice: this.state.product.oldPrice,
                        }];
                        AsyncStorage.setItem("shopCar_" + userId, JSON.stringify(shopCarParam), (error) => {
                            if (error !== null) {
                                console.log(error)
                            } else {
                                this.setState({
                                    loadingStatus: false,
                                    modalShopCarStatus: false,
                                });
                                Toast.showShortBottom("已加入购物车~");
                                CountEmitter.emit("ShopCarRefresh");//刷新购物车
                            }
                        })
                        /*购物车不为空，追加*/
                    } else {
                        let shopCarData = JSON.parse(shopCar);
                        let newShopCar = [];
                        let appendOrAdd = false;//是否出现购物车再次添加的是相同参数
                        /*遍历处理，如果购物车再次添加的是相同参数的，直接在原来基础相加*/
                        for (let n = 0; n < shopCarData.length; n++) {
                            if (shopCarData[n].proId === this.state.product.id
                                && shopCarData[n].proColor === this.state.shopCarColorMsg
                                && shopCarData[n].proSize === this.state.shopCarSizeMsg) {

                                let shopCarParam = {
                                    proId: this.state.product.id,
                                    proMainImg: this.state.product.mainImg,
                                    proName: this.state.product.name,
                                    proColor: this.state.shopCarColorMsg,
                                    proSize: this.state.shopCarSizeMsg,
                                    proNum: parseInt(this.state.shopCarNum) + parseInt(shopCarData[n].proNum),
                                    proNowPrice: this.state.product.nowPrice,
                                    proOldPrice: this.state.product.oldPrice,
                                };

                                newShopCar.push(shopCarParam);
                                appendOrAdd = true;
                            } else {
                                newShopCar.push(shopCarData[n]);
                            }
                        }
                        /*如果购物车已经有了相同的商品，上面遍历追加数量之后，直接放进本地存储*/
                        if (appendOrAdd === true) {
                            AsyncStorage.setItem("shopCar_" + userId, JSON.stringify(newShopCar), (error) => {
                                if (error !== null) {
                                    console.log(error)
                                } else {
                                    this.setState({
                                        loadingStatus: false,
                                        modalShopCarStatus: false,
                                    });
                                    Toast.showShortBottom("已加入购物车~");
                                    CountEmitter.emit("ShopCarRefresh");//刷新购物车
                                }
                            })
                            /*如果加进购物车的是不相同的商品，那就追加好了*/
                        } else {
                            let shopCarParam = [{
                                proId: this.state.product.id,
                                proMainImg: this.state.product.mainImg,
                                proName: this.state.product.name,
                                proColor: this.state.shopCarColorMsg,
                                proSize: this.state.shopCarSizeMsg,
                                proNum: this.state.shopCarNum,
                                proNowPrice: this.state.product.nowPrice,
                                proOldPrice: this.state.product.oldPrice,
                            }];

                            AsyncStorage.setItem("shopCar_" + userId, JSON.stringify(JSON.parse(shopCar).concat(shopCarParam)), (error) => {
                                if (error !== null) {
                                    console.log(error)
                                } else {
                                    this.setState({
                                        loadingStatus: false,
                                        modalShopCarStatus: false,
                                    });
                                    Toast.showShortBottom("已加入购物车~");
                                    CountEmitter.emit("ShopCarRefresh");//刷新购物车
                                }
                            })
                        }
                    }
                })
            })
        }
    };

    /*颜色单选按钮选中事件*/
    _setColorRadioButtonsSelectedOption(selectedOption) {
        this.setState({
            shopCarColorMsg: selectedOption.proProp,
            shopCarColorOption: selectedOption,
        });
    }

    /*颜色单选按钮实现*/
    _radioColorButtons = (list) => {
        /*购物车单选*/
        let butView = list ?
            <RadioButtons
                options={list}
                onSelection={this._setColorRadioButtonsSelectedOption.bind(this)}
                selectedOption={this.state.shopCarColorOption}
                renderOption={(option, selected, onSelect, index) => {
                    let styleText = selected ? {color: '#FFF'} : {color: '#000'};
                    let styleBut = selected ? {backgroundColor: '#000'} : {};
                    return (
                        <TouchableOpacity style={[ShopDetailStyle.shopCarRadioButton, styleBut]} onPress={onSelect}
                                          key={index}>
                            <Text
                                style={[styleText, ShopDetailStyle.shopCarRadioButtonText]}>{option.proProp}</Text>

                        </TouchableOpacity>
                    );
                }
                }
                renderContainer={(optionNodes) => {
                    return <View style={{
                        flexDirection: 'row',
                        justifyContent: 'space-around',
                        borderBottomWidth: utils.autoheight(0.5),
                        borderColor: '#979797',
                        flexWrap: 'wrap',
                    }}>{optionNodes}</View>;
                }}
            />
            :
            <Text>无数据</Text>;
        return butView;
    };

    /*颜色单选按钮选中事件*/
    _setSizeRadioButtonsSelectedOption(selectedOption) {
        this.setState({
            shopCarSizeMsg: selectedOption.proProp,
            shopCarSizeOption: selectedOption,
        })
    }

    /*尺寸单选按钮实现*/
    _radioSizeButtons = (list) => {
        /*购物车单选*/
        let butView = list ?
            <RadioButtons
                options={list}
                onSelection={this._setSizeRadioButtonsSelectedOption.bind(this)}
                selectedOption={this.state.shopCarSizeOption}
                renderOption={(option, selected, onSelect, index) => {
                    let styleText = selected ? {color: '#FFF'} : {color: '#000'};
                    let styleBut = selected ? {backgroundColor: '#000'} : {};
                    return (
                        <TouchableOpacity style={[ShopDetailStyle.shopCarRadioButton, styleBut]} onPress={onSelect}
                                          key={index}>
                            <Text
                                style={[styleText, ShopDetailStyle.shopCarRadioButtonText]}>{option.proProp}</Text>

                        </TouchableOpacity>
                    );
                }
                }
                renderContainer={(optionNodes) => {
                    return <View style={{
                        flexDirection: 'row',
                        justifyContent: 'space-around',
                        borderBottomWidth: utils.autoheight(0.5),
                        borderColor: '#979797',
                        flexWrap: 'wrap',
                    }}>{optionNodes}</View>;
                }}
            />
            :
            <Text>无数据</Text>;
        return butView;
    }
}